package com.warrior.uaa.handler;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.warrior.common.utils.ResponseUtil;
import com.warrior.oauth2.common.properties.SecurityProperties;
import com.warrior.uaa.service.impl.UnifiedLogoutService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 退出登入成功处理类
 *
 * @author warrior
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class OauthLogoutSuccessHandler implements LogoutSuccessHandler {
    private static final String REDIRECT_URL = "redirect_uri";
    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    private final UnifiedLogoutService unifiedLogoutService;
    private final SecurityProperties securityProperties;
    private final ObjectMapper objectMapper;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        if (securityProperties.getAuth().getUnifiedLogout()) {
            unifiedLogoutService.allLogout();
        }

        String redirectUri = request.getParameter(REDIRECT_URL);
        if (StrUtil.isNotEmpty(redirectUri)) {
            //重定向指定的地址
            redirectStrategy.sendRedirect(request, response, redirectUri);
        } else {
            ResponseUtil.responseWriter(objectMapper, response, "登出成功", 0);
        }
    }
}
